package com.clc.comm.util;

import java.io.InputStream;
import java.util.Map;
import java.util.Set;

import com.clc.comm.security.Resources;
import com.clc.test.XStreamTest;
import com.thoughtworks.xstream.XStream;

public class XStreamUtil {
	
	@SuppressWarnings("rawtypes")
	public static <T> T parseXML(InputStream in, Class<T> clzz,
			Map<String, Class> aliasMap) {
		if (null == in)
			return null;
		Object obj = clzz.getInterfaces();
		XStream xstream = new XStream();
		xstream.processAnnotations(clzz);
		for (Map.Entry<String, Class> entry : aliasMap.entrySet()) {
			xstream.alias(entry.getKey(), entry.getValue());
		}
		// InputStream input =
		// (XStreamTest.class.getClassLoader().getResourceAsStream("securitytResources.xml"));
		obj = xstream.fromXML(in);
		return (T) obj;
	}
	@SuppressWarnings("rawtypes")
	public static <T> T parseXML(String xml, Class<T> clzz,
			Map<String, Class> aliasMap) {
		if (aliasMap == null)
			return parseXML(xml, clzz);
		if (StringUtil.isBlank(xml))
			return null;
		Object obj = clzz.getInterfaces();
		XStream xstream = new XStream();
		xstream.processAnnotations(clzz);
		for (Map.Entry<String, Class> entry : aliasMap.entrySet()) {
			xstream.alias(entry.getKey(), entry.getValue());
		}

		// InputStream input =
		// (XStreamTest.class.getClassLoader().getResourceAsStream("securitytResources.xml"));
		obj = xstream.fromXML(xml);
		return (T) obj;
	}

	/**
	 * 将字符串格式的xml转换成java对象，使用annotation
	 * 
	 * @param xml
	 * @param clzz
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static <T> T parseXML(String xml, Class<T> clzz) {
		if (StringUtil.isBlank(xml))
			return null;
		Object obj = clzz.getInterfaces();
		XStream xstream = new XStream();
		xstream.processAnnotations(clzz);
		// InputStream input =
		// (XStreamTest.class.getClassLoader().getResourceAsStream("securitytResources.xml"));
		obj = xstream.fromXML(xml);
		return (T) obj;
	}
	
}
